<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-dialog/paper-dialog.html">
<link rel="import" href="../../bower_components/paper-input/paper-input.html">
<link rel="import" href="../../bower_components/paper-input/paper-input-error.html">
<link rel="import" href="../../bower_components/paper-input/paper-textarea.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../../bower_components/mist-list/mist-list-actions.html">
<link rel="import" href="../../bower_components/mist-list/mist-list-actions-behavior.html">

<link rel="import" href="../helpers/transfer-ownership.html">
<link rel="import" href="../tags/tags-form.html">

<link rel="import" href="schedule-edit.html">
<link rel="import" href="schedule-edit-mrc.html">
<link rel="import" href="schedule-edit-condition.html">
<link rel="import" href="schedule-edit-task.html">

<dom-module id="schedule-actions">
  <template>
    <style include="shared-styles">
      mist-list-actions {
        width: 100%;
      }
    </style>
    
    <tags-form id="tagsdialog" model="[[model]]" items="[[items]]" type="[[type]]"></tags-form>
    <transfer-ownership id="ownershipdialog" user="[[user]]" members="[[_otherMembers(members,items.length)]]" items="[[items]]" type="[[type]]"></transfer-ownership>
    <dialog-element id="confirm"></dialog-element>
    <schedule-edit id="editScheduleDialog" schedule="[[items.0]]" model="[[model]]"></schedule-edit>
    <schedule-edit-mrc id="editMaxRunCount" schedule="[[items.0]]"></schedule-edit-mrc>
    <schedule-edit-task id="editScheduleTask" schedule="[[items.0]]" scripts="[[model.scriptsArray]]"></schedule-edit-task>
    <schedule-edit-condition id="editScheduleCondition" 
        schedule="[[items.0]]" 
        model="[[model]]" 
        machines-age="[[machineAge]]"
        machines-cost="[[machinesCost]]" currency=[[currency]]></schedule-edit-condition>

    <slot>
        <mist-list-actions actions=[[actions]]></mist-list-actions>
    </slot>

    <iron-ajax id="request"
            handle-as="json"
            loading="{{loadingData}}"
            on-response="handleResponse"
            on-error="handleError"></iron-ajax>

  </template>
  <script>
SCHEDULE_ACTIONS = {
  'run': {
    'name': 'run',
    'icon': 'av:play-arrow',
    'confirm': false,
    'multi': false,
    'single': true
  },
  'edit': {
    'name': 'edit',
    'icon': 'editor:mode-edit',
    'confirm': false,
    'multi': false
  },
  'tag': {
    'name': 'tag',
    'icon': 'label',
    'confirm': true,
    'multi': true
  },
  'transfer-ownership': {
    'name': 'transfer ownership',
    'icon': 'icons:redo',
    'confirm': false,
    'multi': true
  },
  'delete': {
    'name': 'delete',
    'icon': 'delete',
    'confirm': true,
    'multi': true
  }
}
    Polymer({ 
      is: 'schedule-actions',
      properties: {
        user: {
            type: String
        },
        members: {
            type: Array
        },
        org: {
            type: Object
        },
        items: { 
          type: Array,
          value: []
        },
        actions: { 
          type: Array,
          value: [],
          notify: true
        },
        type: {
          type: String,
          value: 'schedule'
        },
        inSingleView: {
          type: Boolean,
          reflectToAttribute: true
        },
        machinesCost: {
          type: Number
        },
        currency: {
          type: Object
        }
      },
      observers:[
        '_mapPolicyToActions(items.*,user,org)'
      ],
      listeners: {
        'confirmation': 'confirmAction',
        'transfer-ownership': 'transferOwnership',
        'confirmation': '_actionConfirmed',
        'select-action': 'selectAction'
      },
      attached: function() {
        this.$.request.headers["Content-Type"] = 'application/json';
        this.$.request.headers["Csrf-Token"] = CSRF_TOKEN;
        this.$.request.method = "POST";
      },
      itemActions: function(schedule) {
        // single schedule actions
        var arr = [];
        if (schedule) {
          if (this.inSingleView){
            arr.push('run');
            if (!this._hasExpired(schedule.expires))
              arr.push('edit');
          }
          arr.push('tag');
          if (this.org.ownership_enabled && (schedule.owned_by == this.user || this.org.is_owner)) {
            arr.push('transfer-ownership');
          }
          arr.push('delete');
        }
        return arr;
      },
      _hasExpired: function(expirydate) {
          if (expirydate != undefined && expirydate != "" && expirydate.length > 0){
              return moment().diff(moment.utc(expirydate).local()) > 0;
          }
          else {
              return false;
          }
      },
      actionDetails: function (actions) {
        var ret = [];
        for (var i=0; i<actions.length; i++) {
            ret.push(SCHEDULE_ACTIONS[actions[i]]);
        }
        return ret;
      },
      _otherMembers: function (members,items) {
        if (this.items && members) {
          var owners = this.items.map(function(i){return i.owned_by;})
                            .filter(function(value,index,self){return self.indexOf(value) === index;});
          // filter out pending users and the single owner of the item-set if that is the case
          return members.filter(function(m) {
              return owners.length == 1 ? m.id != owners[0] && !m.pending : !m.pending;
          });
        }
      },
      _delete: function(items) {
        //set up iron ajax
        this.$.request.headers["Content-Type"] = 'application/json';
        this.$.request.headers["Csrf-Token"] = CSRF_TOKEN;
        this.$.request.method = "DELETE";

        for (var i = 0; i < items.length; i++) {
          this.$.request.url = "/api/v1/schedules/"+ items[i].id
          this.$.request.generateRequest();
          this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail:  {msg: 'Deleting ' + items[i].name , duration: 1000} }));
        }
      },
      _showDialog: function(info) {
          var dialog = this.shadowRoot.querySelector('dialog-element');
          for (var i in info) {
              dialog[i] = info[i];
          }
          dialog._openDialog();
      },
      confirmAction: function(e){
        if (e.detail.confirmed) {
          this.performAction(this.action, this.items);
        }
      },
      selectAction: function(e){
        if (this.items.length) {
          var action = e.detail.action;
          this.set('action', action);
          // console.log('perform action mist-action', this.items);
          if (action.confirm && action.name != 'tag') {
            var property = ['zone'].indexOf(this.type) == -1 ? "name" : "domain",
                plural = this.items.length == 1 ? '' : 's',
                count = this.items.length > 1 ? this.items.length+' ' : '';
            //this.tense(this.action.name) + " " + this.type + "s can not be undone. 
            this._showDialog({
                title: this.action.name + ' ' + count + this.type + plural+'?',
                body: "You are about to " + this.action.name + " " + this.items.length + " " + this.type + plural+".",
                list: this._makeList(this.items, property),
                action: action.name,
                danger: true,
                reason: this.type + "." + this.action.name
            });
          }
          else if (action.name == "tag") {
            this.$.tagsdialog._openDialog();
          }
          else if (action.name == 'edit') {
            this._editSchedule();
          }
          else if (action.name == 'run') {
            this._runOnceDialog();
          }
          else if (action.name == 'transfer ownership') {
            this.$.ownershipdialog._openDialog();
          }
          else {
            this.performAction(this.action, this.items);
          }
        }
      },
      performAction: function(action, items) {
        if (action.name == 'delete') {
          this._delete(items);
        }
      },
      transferOwnership: function (e) {
        var payload = {
          user_id: e.detail.user_id, //new owner
          resources: {}
        };
        payload.resources[this.type] = this.items.map(function(i){return i.id});
        console.log('transferOwnership', e.detail, payload);
        this.$.request.url = '/api/v1/ownership';
        this.$.request.headers["Content-Type"] = 'application/json';
        this.$.request.headers["Csrf-Token"] = CSRF_TOKEN;
        this.$.request.method = "POST";
        this.$.request.body = payload;
        this.$.request.generateRequest();
      },
      handleResponse: function(e) {
        if (this.$.request && this.$.request.body && this.$.request.body.action) {
          this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail:  {msg: 'Action: '+this.$.request.body.action+' successfull', duration: 3000} }));
        } else if (this.$.request && this.$.request.body && !this.$.request.body.action) {
          this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: { msg: 'Successfully sent request to run once now.', duration: 3000 } }));
        } else if (this.$.request && this.$.request.method == "DELETE") {
          this.dispatchEvent(new CustomEvent('go-to', { bubbles: true, composed: true, detail:  { url: '/schedules'} }));
        }
        if (e.detail.xhr.responseURL.endsWith("api/v1/ownership") && e.detail.xhr.status == 200 ) {
          this.$.ownershipdialog._closeDialog();
          this.dispatchEvent(new CustomEvent('action-finished'));
          this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: {
            msg: 'Successfull ownership transfer',
            duration: 3000
          } }));
        }
      },
      _mapPolicyToActions: function (items) {
        this.set('actions', []);
        var actions = new swiftSet.Set(), 
            isection = new swiftSet.Set();

        if (this.items.length > 0) {
          actions.addItems(this.itemActions(this.items[0]) || []);

          for (var i=1; i<this.items.length; i++) {
              isection.clear()
              isection.addItems(actions.intersection(this.itemActions(this.items[i])));
              actions.clear();
              actions.addItems(isection.items());
          }

          var multiActions;

          if (this.items.length > 1) {
              multiActions = this.actionDetails(actions.items()).filter(function(a){
                  return a.multi;
              });
          }
          else {
              multiActions = this.actionDetails(actions.items());
          }
        }
        this.set('actions', multiActions);
      },

      handleError: function(e) {
        // console.log(e.detail.request.xhr.statusText);
        this.dispatchEvent(new CustomEvent('toast', { bubbles: true, composed: true, detail: {msg: 'Error: ' + e.detail.request.xhr.status +" "+ e.detail.request.xhr.statusText, duration: 5000} }));

        if (e.detail.request.xhr.responseURL.endsWith("api/v1/ownership")) {
          this.$.ownershipdialog._closeDialog();
        }
      },

      _editSchedule: function(e) {
          this.$.editScheduleDialog._openEditScheduleModal();
      },

      _runOnceDialog: function(e) {
          this._showDialog({
              title: 'Run once now?',
              body: "The schedule will execute once and then continue as planned." ,
              danger: false,
              reason: "schedule.run",
              action: 'run'
          });
      },

      _makeList: function(items, property){
        if (items && items.length)
          return items.map(function(item){
            return item[property];
          });
      },

      _actionConfirmed: function(e) {
          console.log('_actionConfirmed', this.items, e);
          var reason = e.detail.reason,
              response = e.detail.response;
          if (response == 'confirm' && reason == "schedule.delete") {
              this._delete(this.items)
          }

          if (response == 'confirm' && reason == "schedule.run") {
              this.$.request.url = "/api/v1/schedules/"+ this.items[i].id
              this.$.request.method = "PATCH";
              this.$.request.body = {'run_immediately': true}
              this.$.request.headers["Content-Type"] = 'application/json';
              this.$.request.headers["Csrf-Token"] = CSRF_TOKEN;
              this.$.request.generateRequest();
          }
      },
    });
  </script>
</dom-module>